package com.example.msgBoard.controller;

// 导入必要的类
import com.example.msgBoard.model.Message;
import com.example.msgBoard.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;

@RestController
// 表示这是一个RESTful Web服务的控制器
// 自动将返回值序列化为JSON并返回给客户端

@RequestMapping("/api/messages")
// 指定此控制器处理的基本URL路径
public class MessageController {
    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);
    @Autowired
    // 自动注入MessageService的实例
    private MessageService messageService;

    @GetMapping
    // 处理GET请求，路径为"/api/messages"
    public ResponseEntity<List<Message>> getRootMessages() {
        return ResponseEntity.ok(messageService.getAllRootMessages());
    }

    @GetMapping("/{id}")
    // 处理GET请求，路径为"/api/messages/{id}"
    public ResponseEntity<Message> getMessage(@PathVariable int id) {
        Message message = messageService.getMessageById(id);
        if (message != null) {
            return ResponseEntity.ok(message);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/{id}/replies")
    // 处理GET请求，路径为"/api/messages/{id}/replies"
    public List<Message> getReplies(@PathVariable int id) {
        return messageService.getRepliesByParentId(id);
    }

    @PostMapping
    // 处理POST请求，路径为"/api/messages"
    public ResponseEntity<Void> addMessage(@RequestBody Map<String, Object> messageData) {
        logger.info("Received message data: {}", messageData);//日志打印
        // 手动构造 Message 对象
        Message message = new Message();
        message.setContent((String) messageData.get("content"));
        message.setParentId((Integer) messageData.get("parentId"));
        message.setUserId((Integer) messageData.get("userId"));
        message.setUsername((String) messageData.get("username"));
        
        messageService.addMessage(message);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/{id}")
    // 处理PUT请求，路径为"/api/messages/{id}"
    // 该方法用于更新指定ID的消息
    public ResponseEntity<Void> updateMessage(@PathVariable int id, @RequestBody Message message) {
        // 设置消息的ID为URL路径中提取的ID
        message.setId(id);
        // 调用消息服务的更新方法来保存更新后的消息
        messageService.updateMessage(message);
        // 返回200 OK响应，表示消息成功更新
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/{id}")
    // 处理DELETE请求，路径为"/api/messages/{id}"
    public ResponseEntity<Void> deleteMessage(@PathVariable int id) {
        messageService.deleteMessage(id);
        return ResponseEntity.ok().build();
    }
}
